package ejbEMI;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

@Stateless(name = "EMI", mappedName = "myEMIjndi")
public class EMI implements CalcEMI {

    @Override
    public double callEMI(long PA, int term) {
	double emi;
	float interestRate = getInterestRate(term);
	emi = (PA + (PA * term * interestRate) / 100) / (term * 12);
	return emi;
    }

    private float getInterestRate(int term) {
	float interest = 0;
	Context ctx;
	DataSource ds;
	Connection con;
	PreparedStatement stmt;
	ResultSet rs;
	try {
	    ctx = new InitialContext();
	    ds = (DataSource) ctx.lookup("jdbc/mydata");
	    con = ds.getConnection();

	    // con =
	    // DriverManager.getConnection("jdbc:oracle:thin:@10.23.0.100:1521/esgdb10",
	    // "scott","tiger");
	    stmt = con
		    .prepareStatement("Select interest from InterestRate where term= ?");
	    stmt.setInt(1, term);
	    rs = stmt.executeQuery();

	    if (rs.next()) {
		interest = rs.getFloat(1);
	    }
	    stmt.close();
	    con.close();
	} catch (Exception e) {
	    System.out.println(e.toString());
	}
	return interest;
    }
}
// E = P*r*(1 + r)^n/((1 + r)^n - 1)
// E=emi
// p=principal amt
// r=interest rate
// n=months

// SQL:
// create table InterestRate ( term integer primary key, interest float not
// null);
// insert into InterestRate values (5,2.5);
// insert into InterestRate values (10,2);
// insert into InterestRate values (15,1.5);
// insert into InterestRate values (20,1);
// commit;
